#include "bindings/bindings_text_value_run.h"
#include "helpers/general.h"

namespace ohos_rive {

using namespace rive;
static rive::TextValueRun *GetNativePtr(napi_env env, napi_callback_info info)
{
    size_t argc = 1;
    napi_value argv[1];
    napi_value thisArg;
    void *data;

    napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisArg, &data);
    if (status != napi_ok) {
        LOGE("Failed to parse arguments");
        return nullptr;
    }

    if (argc < 1) {
        LOGE("Wrong number of arguments");
        return nullptr;
    }

    // 获取 native 指针
    int64_t nativePtr;
    status = napi_get_value_int64(env, argv[0], &nativePtr);
    if (status != napi_ok) {
        LOGE("Failed to get native pointer");
        return nullptr;
    }

    return reinterpret_cast<rive::TextValueRun *>(nativePtr);
}

napi_value TextValueRunGetText(napi_env env, napi_callback_info info)
{
    auto *run = GetNativePtr(env, info);
    if (run == nullptr) {
        LOGE("Invalid native pointer");
        return nullptr;
    }

    const std::string &text = run->text();
    napi_value result;
    napi_status status = napi_create_string_utf8(env, text.c_str(), text.length(), &result);

    if (status != napi_ok) {
        LOGE("Failed to create string result");
        return nullptr;
    }

    return result;
}

napi_value TextValueRunSetText(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value argv[2];
    napi_value thisArg;
    void *data;

    napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisArg, &data);
    if (status != napi_ok) {
        LOGE("Failed to parse arguments");
        return nullptr;
    }

    if (argc < 2) {
        LOGE("Wrong number of arguments");
        return nullptr;
    }

    auto *run = reinterpret_cast<rive::TextValueRun *>(data);
    if (run == nullptr) {
        // 从参数获取指针
        int64_t nativePtr;
        status = napi_get_value_int64(env, argv[0], &nativePtr);
        if (status != napi_ok) {
            LOGE("Failed to get native pointer");
            return nullptr;
        }
        run = reinterpret_cast<rive::TextValueRun *>(nativePtr);
    }

    if (run == nullptr) {
        LOGE("Invalid native pointer");
        return nullptr;
    }

    // 获取新文本
    size_t textLength;
    status = napi_get_value_string_utf8(env, argv[1], nullptr, 0, &textLength);
    if (status != napi_ok) {
        LOGE("Failed to get text length");
        return nullptr;
    }

    char *buffer = new char[textLength + 1];
    size_t copied;
    status = napi_get_value_string_utf8(env, argv[1], buffer, textLength + 1, &copied);
    if (status != napi_ok) {
        delete[] buffer;
        LOGE("Failed to get text value");
        return nullptr;
    }

    std::string newText(buffer, copied);
    delete[] buffer;

    // 设置新文本
    run->text(newText);

    napi_value result;
    napi_get_undefined(env, &result);
    return result;
}
} // namespace ohos_rive